package com.zsk.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 跨域配置<br>
 * 跨域资源共享 CORS 详解：http://www.ruanyifeng.com/blog/2016/04/cors.html<br/>
 * HTTP 中文开发手册：https://www.php.cn/manual/view/35587.html
 * 
 * @author keke
 * @date 2020/12/05
 */
public class CrossFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chiain)
        throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        // 允许跨域的地址*表示所有
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8848");
        // 表示是否允许发送Cookie
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许跨域的方法
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
        // 预检请求的有效期,OPTIONS请求就是想服务端进行探测支持的方法
        response.setHeader("Access-Control-Max-Age", "3600");
        // 跨域时允许的请求头字段
        response.setHeader("Access-Control-Allow-Headers",
            "Origin, X-Requested-With, Content-Type, Accept,Token,tokenzsk,tokenzsk1");
        // 检测时直接返回
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
        chiain.doFilter(servletRequest, servletResponse);
    }

}
